package com.tyust.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tyust.dao.UserDao;
import com.tyust.model.User;
import com.tyust.util.DbUtil;
import com.tyust.util.StringUtil;

public class LoginServlet extends HttpServlet{
	DbUtil dbUtil = new DbUtil();
	UserDao userDao = new UserDao();
	@Override
	public void service(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		request.setAttribute("userName", userName);
		request.setAttribute("password", password);
		if(StringUtil.isEmpty(userName) || StringUtil.isEmpty(password)){
			request.setAttribute("error", "用户名或密码不能为空！");
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		User user = new User(userName,password);
		Connection con = null;
		try {
			con = dbUtil.getCon();
			User currUser = userDao.login(con,user);
			if(currUser==null){
				request.setAttribute("error", "用户名或密码错误！");
				//服务器跳转
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}else{
				HttpSession session = request.getSession();
				session.setAttribute("currUser", currUser);
				//客户端跳转
				response.sendRedirect("main.jsp");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
